import { Link, NavLink, Outlet, useNavigate } from 'react-router-dom';
import { Layout, Menu, Dropdown, Button, Input } from 'antd';
import { 
  SearchOutlined, 
  MenuOutlined,
  GlobalOutlined,
  DownOutlined 
} from '@ant-design/icons';
import { useState, useEffect } from 'react';
import logo from '../assets/logo.png';
import './MainLayout.css';
import BackToTop from '../components/BackToTop';

const { Header } = Layout;

interface NavItem {
  path: string;
  enPath: string;
  label: string;
  enLabel: string;
  end?: boolean;
  children?: NavItem[]; // 添加子菜单项
}

export default function MainLayout() {
  const navigate = useNavigate();
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);
  const [visibleNavItems, setVisibleNavItems] = useState<NavItem[]>([]);
  const [hiddenNavItems, setHiddenNavItems] = useState<NavItem[]>([]);
  const [searchVisible, setSearchVisible] = useState(false);
  const [language, setLanguage] = useState<'zh' | 'en'>(() => {
    return localStorage.getItem('language') as 'zh' | 'en' || 'zh';
  });

  const navItems: NavItem[] = [
    { 
      path: '/', 
      enPath: '/en', 
      label: '首页', 
      enLabel: 'Home', 
      end: true 
    },
    { 
      path: '/about', 
      enPath: '/en/about', 
      label: '关于我们', 
      enLabel: 'About' 
    },
    { 
      path: '/services', 
      enPath: '/en/services', 
      label: '产品中心', 
      enLabel: 'Products',
      children: [
        { 
          path: '/services/software', 
          enPath: '/en/services/software', 
          label: '软件产品', 
          enLabel: 'Software' 
        },
        { 
          path: '/services/hardware', 
          enPath: '/en/services/hardware', 
          label: '硬件产品', 
          enLabel: 'Hardware' 
        },
        { 
          path: '/services/custom', 
          enPath: '/en/services/custom', 
          label: '定制开发', 
          enLabel: 'Custom Solutions' 
        }
      ]
    },
    { 
      path: '/cases', 
      enPath: '/en/cases', 
      label: '案例中心', 
      enLabel: 'Cases',
      children: [
        { 
          path: '/cases/finance', 
          enPath: '/en/cases/finance', 
          label: '金融行业', 
          enLabel: 'Finance' 
        },
        { 
          path: '/cases/education', 
          enPath: '/en/cases/education', 
          label: '教育行业', 
          enLabel: 'Education' 
        },
        { 
          path: '/cases/government', 
          enPath: '/en/cases/government', 
          label: '政府机构', 
          enLabel: 'Government' 
        }
      ]
    },
    { 
      path: '/news', 
      enPath: '/en/news', 
      label: '新闻中心', 
      enLabel: 'News' 
    },
    { 
      path: '/contact', 
      enPath: '/en/contact', 
      label: '联系我们', 
      enLabel: 'Contact' 
    }
  ];

  useEffect(() => {
    const handleResize = () => {
      setWindowWidth(window.innerWidth);
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  useEffect(() => {
    const calculateVisibleItems = () => {
      const availableWidth = windowWidth - 400;
      const maxVisibleItems = Math.max(0, Math.floor(availableWidth / 100));
      
      setVisibleNavItems(navItems.slice(0, maxVisibleItems));
      setHiddenNavItems(navItems.slice(maxVisibleItems));
    };

    calculateVisibleItems();
  }, [windowWidth]);

  const handleSearchClick = () => {
    const searchPath = language === 'zh' ? '/search' : '/en/search';
    navigate(searchPath);
  };

  const handleLanguageChange = (lang: 'zh' | 'en') => {
    setLanguage(lang);
    localStorage.setItem('language', lang);
    const currentPath = window.location.pathname;
    let newPath = currentPath;
    
    if (lang === 'en') {
      if (currentPath === '/') {
        newPath = '/en';
      } else if (!currentPath.startsWith('/en')) {
        newPath = `/en${currentPath}`;
      }
    } else {
      if (currentPath === '/en') {
        newPath = '/';
      } else if (currentPath.startsWith('/en')) {
        newPath = currentPath.replace('/en', '');
      }
    }
    
    navigate(newPath);
  };

  const renderDropdownMenu = (items: NavItem[]) => (
    <Menu>
      {items.map((item, index) => (
        <Menu.Item key={index}>
          <NavLink to={language === 'zh' ? item.path : item.enPath}>
            {language === 'zh' ? item.label : item.enLabel}
          </NavLink>
        </Menu.Item>
      ))}
    </Menu>
  );

  const navMenu = (
    <Menu>
      {hiddenNavItems.map((item, index) => (
        <Menu.Item key={index}>
          {item.children ? (
            <Dropdown overlay={renderDropdownMenu(item.children)} placement="bottomRight">
              <div>
                <NavLink to={language === 'zh' ? item.path : item.enPath}>
                  {language === 'zh' ? item.label : item.enLabel} <DownOutlined />
                </NavLink>
              </div>
            </Dropdown>
          ) : (
            <NavLink to={language === 'zh' ? item.path : item.enPath}>
              {language === 'zh' ? item.label : item.enLabel}
            </NavLink>
          )}
        </Menu.Item>
      ))}
    </Menu>
  );

  const languageMenu = (
    <Menu>
      <Menu.Item key="zh" onClick={() => handleLanguageChange('zh')}>
        中文
      </Menu.Item>
      <Menu.Item key="en" onClick={() => handleLanguageChange('en')}>
        English
      </Menu.Item>
    </Menu>
  );

  return (
    <Layout className="app-root">
      <Header className="site-header">
        <div className="header-inner">
          <Link to={language === 'zh' ? '/' : '/en'} className="logo">
            <img src={logo} alt="KAIZELI Logo" />
            <div className="logo-text">
              <div className="logo-text-zh">广州凯泽利科技有限公司</div>
              <div className="logo-text-en">Guangzhou Kaizeli Technology Co., Ltd.</div>
            </div>
          </Link>
          <nav className="nav">
            {visibleNavItems.map((item, index) => (
              item.children ? (
                <Dropdown 
                  key={index} 
                  overlay={renderDropdownMenu(item.children)} 
                  placement="bottomCenter"
                  trigger={['hover']}
                >
                  <div className="nav-dropdown">
                    <NavLink 
                      to={language === 'zh' ? item.path : item.enPath}
                      end={item.end}
                    >
                      {language === 'zh' ? item.label : item.enLabel}
                    </NavLink>
                  </div>
                </Dropdown>
              ) : (
                <NavLink 
                  key={index} 
                  to={language === 'zh' ? item.path : item.enPath} 
                  end={item.end}
                >
                  {language === 'zh' ? item.label : item.enLabel}
                </NavLink>
              )
            ))}
            
            {hiddenNavItems.length > 0 && (
              <Dropdown overlay={navMenu} placement="bottomRight">
                <Button type="text" icon={<MenuOutlined />} />
              </Dropdown>
            )}
            
            <Button 
              type="text" 
              icon={<SearchOutlined />} 
              onClick={handleSearchClick}
            />
            
            <Dropdown overlay={languageMenu} placement="bottomRight">
              <Button type="text" icon={<GlobalOutlined />}>
                {language === 'zh' ? '中文' : 'EN'}
              </Button>
            </Dropdown>
          </nav>
        </div>
      </Header>

      <main className="site-main">
        <Outlet />
      </main>
      <BackToTop />
    </Layout>
  );
}